<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="就诊卡号" prop="cardId">
        <el-input
          v-model="queryParams.cardId"
          placeholder="请输入就诊卡号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="病人姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入病人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室" prop="departmentId">
        <el-select
          v-model="queryParams.departmentId"
          placeholder="请选择科室"
          clearable
        >
          <el-option
            v-for="dict in td_department"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="挂号日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="挂号时间" prop="time">
        <el-select
          v-model="queryParams.time"
          placeholder="请选择挂号时间段"
          clearable
        >
          <el-option
            v-for="dict in time"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="挂号类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择普通挂号/预约挂号"
          clearable
        >
          <el-option
            v-for="dict in register_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="挂号状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择挂号状态"
          clearable
        >
          <el-option
            v-for="dict in register_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['index']"
          >新增挂号</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="registerList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="就诊卡号" align="center" prop="cardId" />
      <el-table-column label="病人姓名" align="center" prop="patientName" />
      <el-table-column label="挂号科室" align="center" prop="departmentId">
        <template #default="scope">
          <dict-tag :options="td_department" :value="scope.row.departmentId" />
        </template>
      </el-table-column>
      <el-table-column label="医生姓名" align="center" prop="docterName" />
      <el-table-column
        label="挂号日期"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="挂号时间" align="center" prop="time">
        <template #default="scope">
          <dict-tag :options="time" :value="scope.row.time" />
        </template>
      </el-table-column>
      <el-table-column label="挂号类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="register_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="挂号状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="register_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['index']"
            >退号</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改挂号对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <!-- 上半部分 - 表单 -->
      <div class="form-section">
        <el-form
          ref="registerRef"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="就诊卡号" prop="cardId">
            <el-input
              v-model="form.cardId"
              placeholder="请输入就诊卡号"
              @blur="fetchPatientName"
            />
          </el-form-item>
          <el-form-item label="病人姓名" prop="patientName">
            <el-input
              v-model="form.patientName"
              placeholder="请输入病人姓名"
              readonly
            />
          </el-form-item>
          <el-form
            ref="registerRef"
            :model="form"
            :rules="rules"
            label-width="100px"
          >
            <el-row :gutter="20">
              <!-- 医生姓名 -->
              <el-col :span="12">
                <el-form-item label="医生姓名" prop="docterName">
                  <el-input
                    v-model="form.docterName"
                    placeholder="请选择医生"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <!-- 挂号科室 -->
              <el-col :span="12">
                <el-form-item label="挂号科室" prop="departmentId">
                  <template #default>
                    <div class="blue-highlight">
                      <dict-tag
                        :options="td_department"
                        :value="form.departmentId"
                      />
                    </div>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <!-- 挂号日期 -->
              <el-col :span="12">
                <el-form-item label="挂号日期" prop="scheduleDate">
                  <el-input
                    v-model="form.scheduleDate"
                    placeholder="请选择排班日期"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <!-- 挂号时间 -->
              <el-col :span="12">
                <el-form-item label="挂号时间" prop="time">
                  <template #default>
                    <div class="blue-highlight">
                      <dict-tag :options="time" :value="form.time" />
                    </div>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-form>
      </div>
      <!-- 中部分 - 排班信息列表筛选 -->
      <div class="form-section">
        <el-form
          :model="schedulequeryParams"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="科室" prop="departmentId">
            <el-select
              v-model="schedulequeryParams.departmentId"
              placeholder="请选择科室"
              clearable
            >
              <el-option
                v-for="dict in td_department"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getTodaySchedules"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetScheduleQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!-- 下半部分 - 排班信息列表 -->
      <div class="schedule-section">
        <el-table
          :data="scheduleList"
          @row-click="handleRowClick"
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="医生姓名" align="center" prop="docterName" />
          <el-table-column
            label="排班日期"
            align="center"
            prop="scheduleDate"
            width="180"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.scheduleDate, "{y}-{m}-{d}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="时间段" align="center" prop="time">
            <template #default="scope">
              <dict-tag :options="time" :value="scope.row.time" />
            </template>
          </el-table-column>
          <el-table-column label="科室" align="center" prop="departmentId">
            <template #default="scope">
              <dict-tag
                :options="td_department"
                :value="scope.row.departmentId"
              />
            </template>
          </el-table-column>
          <el-table-column label="剩余号源" align="center" prop="sycount" />
        </el-table>
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="open = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Register">
import {
  listRegister,
  getRegister,
  delRegister,
  addRegister,
  updateRegister,
} from "@/api/clinic/register";

import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import { listSchedulelist } from "@/api/schedule/schedulelist";
import { getPatientNameByCardId } from "@/api/patients/patientlist";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const { time, register_type, td_department, register_status } = proxy.useDict(
  "time",
  "register_type",
  "td_department",
  "register_status"
);

const registerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const scheduleList = ref([]); //排班列表

const startOfToday = new Date();
startOfToday.setHours(0, 0, 0, 0); // 设置为今天的开始时间（00:00:00）

const endOfToday = new Date();
endOfToday.setHours(23, 59, 59, 999); // 设置为今天的结束时间（23:59:59）

const today = new Date().toISOString().slice(0, 10); // 获取今天的日期，格式为 YYYY-MM-DD

const data = reactive({
  form: {
    registerId: null,
    cardId: "",
    patientName: "",
    patientId: null, // 确保有 patientsId 字段
    docterName: "",
    docterId: null, // 确保有 docterId 字段
    departmentId: "",
    scheduleDate: "",
    time: null,
    scheduleId: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cardId: null,
    patientName: null,
    docterName: null,
    departmentId: null,
    departmentName: null,
    createTime: null,
    time: null,
    type: null,
    status: null,
    scheduleId: null,
  },
  schedulequeryParams: {
    pageNum: 1,
    pageSize: 10,
    departmentId: null,
    time: null,
    scheduleDate: new Date().toISOString().slice(0, 10), // 默认值为今天
    params: {}, // 添加 params 对象
  },
  rules: {
    cardId: [{ required: true, message: "就诊卡号不能为空", trigger: "blur" }],
  },
  errorMessage: "",
});

const { queryParams, form, rules, schedulequeryParams } = toRefs(data);

// 获取排班信息列表
const getTodaySchedules = async () => {
  loading.value = true;
  const today = new Date().toISOString().slice(0, 10); // 获取今天的日期，格式为 YYYY-MM-DD

  // 设置 beginScheduleDate 和 endScheduleDate 为今天的日期
  schedulequeryParams.value.params = {
    beginScheduleDate: today,
    endScheduleDate: today,
  };

  // 调用后端 API
  listSchedulelist(schedulequeryParams.value)
    .then((response) => {
      scheduleList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    })
    .catch((error) => {
      ElMessage.error("获取排班信息失败");
      loading.value = false;
    });
};
// 重置排班信息列表筛选条件
const resetScheduleQuery = () => {
  schedulequeryParams.value = {
    pageNum: 1,
    pageSize: 10,
    departmentId: null,
    time: null,
    params: {}, // 重置 params 对象
  };
  getTodaySchedules(); // 重置后重新获取数据
};

// 处理排班信息行点击事件
const handleRowClick = (row) => {
  form._object.form.docterName = row.docterName;
  form._object.form.departmentId = row.departmentId;
  form._object.form.scheduleDate = row.scheduleDate;
  form._object.form.time = row.time;
  form._object.form.scheduleId = row.id;
  form._object.form.docterId = row.docterId; // 确保获取医生 ID
};

/** 根据就诊卡号查询病人姓名 */
const fetchPatientName = async () => {
  if (form.value.cardId) {
    try {
      const response = await getPatientNameByCardId(form.value.cardId);
      if (response.patientName) {
        form.value.patientName = response.patientName;
        form.value.patientId = response.patientsId;
        console.log("Patient ID set:", form.value.patientId); // 调试输出
      } else {
        ElMessage.warning("该卡号不存在");
      }
    } catch (error) {
      ElMessage.warning("系统异常");
    }
  }
};

/** 查询挂号列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && "" != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listRegister(queryParams.value).then((response) => {
    registerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    registerId: null,
    cardId: null,
    patientsId: null,
    patientName: null,
    docterId: null,
    docterName: null,
    departmentId: null,
    departmentName: null,
    scheduleId: null,
    createTime: null,
    time: null,
    type: null,
    status: null,
  };
  proxy.resetForm("registerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.registerId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加挂号";
  getTodaySchedules();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _registerId = row.registerId || ids.value;
  getRegister(_registerId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改挂号";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["registerRef"].validate((valid) => {
    if (valid) {
      if (form.value.registerId != null) {
        updateRegister(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRegister(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _registerIds = row.registerId || ids.value;
  proxy.$modal
    .confirm('是否确认退号？')
    .then(function () {
      return delRegister(_registerIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("退号成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "clinic/register/export",
    {
      ...queryParams.value,
    },
    `register_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
.blue-highlight {
  background-color: #d9ecff; /* 浅蓝色背景 */
  padding: 8px 16px; /* 内边距 */
  border-radius: 4px; /* 圆角 */
  display: inline-block; /* 确保它作为块级元素内联显示 */
  font-size: 14px; /* 字体大小 */
  color: #1890ff; /* 文字颜色 */
  line-height: 1.5; /* 行高 */
}
</style>
